// ThirdActivity.kt
package com.example.cardgame

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat

class ThirdActivity : AppCompatActivity() {
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var usernameInput: EditText
    private lateinit var emailInput: EditText
    private lateinit var numberInput: EditText
    private lateinit var phoneInput: EditText
    private lateinit var sexGroup: RadioGroup
    private lateinit var maleRadioButton: RadioButton
    private lateinit var femaleRadioButton: RadioButton
    private lateinit var hobbyTravel: CheckBox
    private lateinit var hobbyReading: CheckBox
    private lateinit var hobbyGaming: CheckBox
    private lateinit var hobbyShopping: CheckBox
    private lateinit var userAvatar: ImageView
    private lateinit var takePhotoButton: Button

    private val takePicture = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val imageBitmap = result.data?.extras?.get("data") as? Bitmap
            if (imageBitmap != null) {
                userAvatar.setImageBitmap(imageBitmap)
                saveAvatarToPreferences(imageBitmap) // 调用保存头像的方法
            } else {
                Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "取消拍照", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        WindowCompat.setDecorFitsSystemWindows(window, false)
        setContentView(R.layout.activity_third)

        sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE)
        usernameInput = findViewById(R.id.username_input)
        emailInput = findViewById(R.id.email_input)
        numberInput = findViewById(R.id.number_input)
        phoneInput = findViewById(R.id.phone_input)
        sexGroup = findViewById(R.id.sex_group)
        maleRadioButton = findViewById(R.id.male)
        femaleRadioButton = findViewById(R.id.female)
        hobbyTravel = findViewById(R.id.hobby_travel)
        hobbyReading = findViewById(R.id.hobby_reading)
        hobbyGaming = findViewById(R.id.hobby_gaming)
        hobbyShopping = findViewById(R.id.hobby_shopping)
        userAvatar = findViewById(R.id.user_avatar)
        takePhotoButton = findViewById(R.id.take_photo_button)

        val saveButton: Button = findViewById(R.id.save_button)
        val cancelButton: Button = findViewById(R.id.cancel_button)

        saveButton.setOnClickListener {
            saveUserInfo()
            finish()
        }

        cancelButton.setOnClickListener {
            finish()
        }

        takePhotoButton.setOnClickListener {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
            } else {
                launchCamera()
            }
        }

        loadUserInfo()
    }

    private fun loadUserInfo() {
        val username = sharedPreferences.getString("username", "")
        val email = sharedPreferences.getString("email", "")
        val number = sharedPreferences.getString("number", "")
        val phone = sharedPreferences.getString("phone", "")
        val sex = sharedPreferences.getString("sex", "")
        val hobby = sharedPreferences.getString("hobby", "")
        val avatar = sharedPreferences.getString("avatar", "")

        usernameInput.setText(username)
        numberInput.setText(number)
        emailInput.setText(email)
        phoneInput.setText(phone)

        if (sex == "男") {
            maleRadioButton.isChecked = true
        } else if (sex == "女") {
            femaleRadioButton.isChecked = true
        }

        hobbyTravel.isChecked = hobby?.contains("旅游") == true
        hobbyReading.isChecked = hobby?.contains("阅读") == true
        hobbyGaming.isChecked = hobby?.contains("游戏") == true
        hobbyShopping.isChecked = hobby?.contains("购物") == true

        if (avatar != null && avatar.isNotEmpty()) {
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, Uri.parse(avatar))
            userAvatar.setImageBitmap(bitmap)
        }
    }

    private fun saveUserInfo() {
        val username = usernameInput.text.toString()
        val email = emailInput.text.toString()
        val number = numberInput.text.toString()
        val phone = phoneInput.text.toString()
        val sex = if (maleRadioButton.isChecked) "男" else "女"
        val hobbies = mutableListOf<String>()
        if (hobbyTravel.isChecked) hobbies.add("旅游")
        if (hobbyReading.isChecked) hobbies.add("阅读")
        if (hobbyGaming.isChecked) hobbies.add("游戏")
        if (hobbyShopping.isChecked) hobbies.add("购物")
        val hobby = hobbies.joinToString(", ")
        val avatar = sharedPreferences.getString("avatar", "")

        with(sharedPreferences.edit()) {
            putString("username", username)
            putString("email", email)
            putString("number", number)
            putString("phone", phone)
            putString("sex", sex)
            putString("hobby", hobby)
            putString("avatar", avatar) // 保存头像 URI
            apply()
        }
    }

    private fun saveAvatarToPreferences(bitmap: Bitmap?) {
        if (bitmap == null) {
            Toast.makeText(this, "保存头像失败", Toast.LENGTH_SHORT).show()
            return
        }
        val uri = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "avatar", null)
        with(sharedPreferences.edit()) {
            putString("avatar", uri)
            apply()
        }
    }

    private fun launchCamera() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        takePicture.launch(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                launchCamera()
            } else {
                Toast.makeText(this, "相机权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }

    companion object {
        private const val REQUEST_CAMERA_PERMISSION = 1
    }
}